package com.zhouyibike.uu.ui.activity.mybike;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.BuyBikeListResult;
import com.zhouyibike.uu.entity.BuyBikeResult;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.WXBikeBuyResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.adapter.BuyBikeListAdapter;
import com.zhouyibike.uu.ui.adapter.YiXuanBikeListAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class BuyBikeActivity extends BaseActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private GridView gv_list,gv_yixuan;
    private LinearLayout ll_yixuan;
    private TextView tv_buynum,tv_totalmoney;
    private CheckBox cb_wx,cb_zfb;
    private Button btn_buy;

    private BuyBikeListAdapter myBikeAdapter;
    private YiXuanBikeListAdapter yiXuanBikeListAdapter;
    private HashMap<String,Double> presstag=new HashMap<>();//数据为钱
    private List<String> pressnumber=new ArrayList<>();//数据为车号
    private List<String> pressid=new ArrayList<>();//数据为车号
    private double totalprice=0;
    private String paytype="1";
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_bike);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        initView();
        getMsg();
    }
    private void initView() {
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("我的单车");
        mBtnBack.setOnClickListener(this);
        gv_list= (GridView) findViewById(R.id.gv_buybike_list);
        ll_yixuan= (LinearLayout) findViewById(R.id.ll_buybike_yixuan);
        gv_yixuan= (GridView) findViewById(R.id.gv_buybike_yxlist);
        tv_buynum= (TextView) findViewById(R.id.tv_buybike_buynum);
        tv_totalmoney= (TextView) findViewById(R.id.tv_buybike_totalmoney);
        cb_wx= (CheckBox) findViewById(R.id.cb_buybike_wx);
        cb_wx.setOnCheckedChangeListener(this);
        cb_zfb= (CheckBox) findViewById(R.id.cb_buybike_zfb);
        cb_zfb.setOnCheckedChangeListener(this);
        btn_buy= (Button) findViewById(R.id.btn_buybike_buy);
        btn_buy.setOnClickListener(this);
    }
    private void getMsg(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        showProgressDialog();
        addSubscription(apiStores.BuyBicycleList(params),
                new ApiCallback<BuyBikeListResult>() {

                    @Override
                    public void onSuccess(BuyBikeListResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
                            if(model.getData().size()==0){
                                gv_list.setVisibility(View.GONE);
                            }else{
                                gv_list.setVisibility(View.VISIBLE);
                                initList(model);
                            }
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    private void initYixuan(){
        yiXuanBikeListAdapter=new YiXuanBikeListAdapter(this,pressnumber);
        gv_yixuan.setAdapter(yiXuanBikeListAdapter);
    }
    private void initList(BuyBikeListResult model){
        myBikeAdapter=new BuyBikeListAdapter(this,model.getData());
        gv_list.setAdapter(myBikeAdapter);
        gv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                myBikeAdapter.setpreid(view.getTag().toString());
                TextView tv= (TextView) view.findViewById(R.id.tv_itemchongzhi_p);
                if(presstag.containsKey(view.getTag().toString())){
                    presstag.remove(view.getTag().toString());
                    totalprice=totalprice- Double.parseDouble(view.findViewById(R.id.tv_itemchongzhi_p).getTag().toString());
                    pressnumber.remove(tv.getText().toString());
                    pressid.remove(view.getTag().toString());
                }else {
                    presstag.put(view.getTag().toString(), Double.parseDouble(view.findViewById(R.id.tv_itemchongzhi_p).getTag().toString()));
                    totalprice=totalprice+ Double.parseDouble(view.findViewById(R.id.tv_itemchongzhi_p).getTag().toString());
                    pressnumber.add(tv.getText().toString());
                    pressid.add(view.getTag().toString());
                }
                if(totalprice==0){
                    ll_yixuan.setVisibility(View.GONE);
                    btn_buy.setEnabled(false);
                }else{
                    btn_buy.setEnabled(true);
                    ll_yixuan.setVisibility(View.VISIBLE);
                    initYixuan();
                }
                tv_buynum.setText(pressnumber.size()+"辆");
                tv_totalmoney.setText(totalprice+"");
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.btn_buybike_buy:
                buybike();
                break;
        }
    }
    private void buybike(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        if(pressid.size()==1){
            params.put("bicycleIds" , pressid.get(0));
        }else {
            for (int i = 0; i < pressid.size(); i++) {
                params.put("bicycleIds[" + i + "]", pressid.get(i));
            }
        }
        showProgressDialog();
        addSubscription(apiStores.BuyBicycles(params),
                new ApiCallback<BuyBikeResult>() {

                    @Override
                    public void onSuccess(BuyBikeResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
                            if(paytype.equals("1")){
                                wxpay(model);
                            }else{
                                zfbpay(model.getData().getAlipay());
                            }
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });

    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.cb_buybike_wx:
                if(isChecked){
                    cb_zfb.setChecked(false);
                    paytype="1";
                }else{
                    cb_zfb.setChecked(true);
                    paytype="2";
                }
                break;
            case R.id.cb_buybike_zfb:
                if(isChecked){
                    cb_wx.setChecked(false);
                    paytype="2";
                }else{
                    cb_wx.setChecked(true);
                    paytype="1";
                }
                break;
        }
    }
    private void paysuccess(){
        setResult(1);
        finish();
    }

    private void wxpay(BuyBikeResult model){
        Log.e("lyl",model.getData().getWeChat());
        WXBikeBuyResult wxBikeBuyResult=new Gson().fromJson(model.getData().getWeChat(),WXBikeBuyResult.class);
        api.registerApp(wxBikeBuyResult.getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if(!isPaySupported){
            Toast.makeText(BuyBikeActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(BuyBikeActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try{
            PayReq request = new PayReq();

            request.appId = wxBikeBuyResult.getAppId();

            request.partnerId = wxBikeBuyResult.getPartnerId();

            request.prepayId=wxBikeBuyResult.getPrepayId();

            request.packageValue ="Sign=WXPay";

            request.nonceStr= wxBikeBuyResult.getNoncestr();

            request.timeStamp=wxBikeBuyResult.getTimestamp();

            request.sign= wxBikeBuyResult.getSign();

            api.sendReq(request);

        }catch(Exception e){
            Toast.makeText(BuyBikeActivity.this, "异常："+e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if(progress==0){//支付成功
            paysuccess();
        }else{
            Toast.makeText(BuyBikeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }
    private void zfbpay(final String orderinfo){

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(BuyBikeActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(BuyBikeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
